#include <util/db.h>
#include <util/md5.h>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/fstream.hpp>
#include <apps/photo/photodb.h>
#include <vector>
#include <iostream>

namespace bfs = boost::filesystem;

struct db_entry {
	std::string id;
	std::string filename;
};
typedef std::vector<db_entry> db_list_t;

static void build_list( db_list_t& list, const adobe::dictionary_t& dict ) {
	db_entry dbe;
	dbe.id = dict.get<std::string>( adobe::static_name_t( "id" ) );
	dbe.filename = dict.get<std::string>( adobe::static_name_t( "filename" ) );
	list.push_back( dbe );
}

int main() {
	db_list_t photos;
	util::db_ptr_t db( util::db::fromPath( apps::photo::getPhotoDatabasePath() ) );
	db->query( "select id, filename from photos;", boost::bind( &build_list, boost::ref( photos ), _1 ) );
	std::cout << photos.size() << " photos to sum" << std::endl;

	for( db_list_t::iterator i = photos.begin(); i != photos.end(); i++ ) {
		std::string filename( i->filename.substr( 7 ) );
		bfs::path p( filename, bfs::native );
		if( !bfs::exists( p ) ) {
			std::cout << "x";
			continue;
		}
		bfs::filebuf bbuf;
		std::streambuf* sbuf = bbuf.open( p, std::ios_base::in | std::ios_base::binary );
		if( !sbuf ) return false;
		std::string sum( util::md5( sbuf, 10240 ) );
		//
		// Now set it into the DB.
		//
		db->execute( "update photos set sum = '" + sum + "' where id = " + i->id + ";" );

		std::cout << "+";
	}

	std::cout << std::endl << std::endl << "done." << std::endl;
	return 0;
}
